import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:jiajia_diy/data/data_base.dart';
import 'package:jiajia_diy/diyProject/diy.dart';
import 'package:jiajia_diy/pages/diy_add_page.dart';
import 'package:jiajia_diy/pages/diy_details_page.dart';
import 'package:jiajia_diy/pages/analyse_page.dart';
import 'package:jiajia_diy/ui/diy_item_card.dart';
import 'package:jiajia_diy/ui/icon_font.dart';
import 'dart:async';
//import 'package:diamond_fab/diamond_fab.dart';

/*
app主页，包含标题栏，底部导航栏和中间展示区域
默认展示diy活动页
 */
class HomePage extends StatefulWidget {
  HomePage({Key key,this.isThemeLight, this.onChanged}) : super(key: key);
  ValueChanged<bool> onChanged;
  bool isThemeLight;

  @override
  State<StatefulWidget> createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
  //实例化数据库对象
  var _db = new DatabaseHelper();
  //实例化diy项目列表
  List<Diy> _diyItems = [];
  //定义滑动控制器实例
  final SlidableController slidableController = new SlidableController();

   _handleTap(){
    widget.onChanged(!widget.isThemeLight);
   }

  //初始化数据
  @override
  void initState() {
    super.initState();
    _readToDiyList();
  }

  //将数据库内的数据添加到列表List<Diy>
  _readToDiyList() async {
    List diyList = await _db.getDiys();
    print('开始初始化数据');
    _diyItems.clear();
    setState(() {
      diyList.forEach((diy) => _diyItems.add(Diy.fromMap(diy)));
    });
  }

  //进入diy新增页面，同时接收返回的数据
  Future addDiy() async {
    final result = await Navigator.of(context)
        .push(new CupertinoPageRoute(fullscreenDialog: true, builder: (context) {
      return DiyAdd( db: _db, diyItems: _diyItems,);
    }));
    setState(() {
      if (result != null) {
        _diyItems = result;
      } else
        return null;
    });
  }

  //弹窗对话框确认是否删除
  _alertDialgIsDelete(index) {
    showDialog(
      context: context,
      builder: (context) {
        return new CupertinoAlertDialog(
          title: new Text('是否确认删除?'),
          content: new Text('此次操作无法挽回，你将彻底失去我'),
          actions: <Widget>[
            new CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: new Text('再想想')),
            new CupertinoDialogAction(
              onPressed: () {
                _handleDeleteDiyItem(index);
                Navigator.pop(context);
              },
              child: new Text(
                '不要了',
                style: new TextStyle(color: Colors.red),
              ),
            ),
          ],
        );
      },
    );
  }

  //从数据库库删除数据，然后重新从数据库获取数据并刷新
  _handleDeleteDiyItem(index) async {
    int id = _diyItems[index].id;
    await _db.deleteDiy(id);
    _readToDiyList();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('活動展示'),
        actions: <Widget>[
          new IconButton(
             icon: new Icon(Icons.face),
              onPressed: () => _handleTap(),
          )
        ],
      ),
      body: new ListView.builder(
         itemBuilder: (context,index){
           if (index < _diyItems.length) {
              //返回一个支持滑动抽屉菜单的控件
              return new Slidable(
                controller: slidableController, //保持只有一个滑动抽屉存在
                delegate: new SlidableDrawerDelegate(), //幻灯片方式的滑动
                actionExtentRatio: 0.25,
                secondaryActions: <Widget>[
                  new IconSlideAction(
                    //closeOnTap: false,
                    icon: Icons.border_color,
                    color: Colors.blueAccent,
                    caption: '编辑',
                    onTap: () {},
                  ),
                  new IconSlideAction(
                    icon: Icons.delete,
                    color: Colors.red,
                    caption: '删除',
                    onTap: () => _alertDialgIsDelete(index),
                  ),
                ],
                //带水波纹效果的手势识别控件
                child: new InkWell(
                  onTap: () {
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return new DiyDetails(db: _db, diyItem: _diyItems[index], diyItems: _diyItems,);
                    }));
                  },
                  child: new DiyItemUI(_diyItems[index]),
                ),
              );
            }
         },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.add),
        onPressed: (){
          addDiy();
        },
      ),
      bottomNavigationBar: new BottomAppBar(
        notchMargin: 6.0,
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            new IconButton(
              icon: new Icon(Icons.search),
              onPressed: () {},
            ),
            new IconButton(
              icon: new Icon(Icons.subject),
              onPressed: () {
                Navigator.of(context).push(new MaterialPageRoute( builder: (context){
                   return new StatisticalAnalysis( db: _db,);
                }));
              },
            )
          ],
        ),
      ),
    );
  }
}
